﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ESupervision.Models;
using Microsoft.AspNet.Identity;
using ESupervision.ViewModels;


namespace ESupervision.Controllers
{
    [Authorize]
    public class DashboardController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: /StudentDashboard/

        [Authorize(Roles = "Student")]
        public ActionResult Index()
        {
            DashboardSumarising dashboard = new DashboardSumarising();// Create new View Model
            string userId = User.Identity.GetUserId(); // Get current User
            dashboard.TotalSentMessages = (from m in db.MessageSents where m.SentUserID == userId select m).Count();//Get Total Sent Messages
            dashboard.TotalInboxMessages = (from m in db.MessageRecipients where m.ReceiverUserID == userId select m).Count();//Get Total Inbox Messages
            dashboard.TotalUploadedFiles = (from d in db.Documents where d.CreatedByUserId == userId select d).Count();//Get Total uploaded files
            dashboard.TotalComments = (from c in db.Comments where c.UserId == userId select c).Count();//Get Total Comments in file uploaded
            dashboard.TotalRequestedMeetings = (from m in db.MeetingEventParticipants where m.RequestedUserID == userId select m).Count();//Get Total Requested Meetings
            dashboard.StaticStudent = db.Students.Find(userId);//Get supervision and second marker profile
            dashboard.Convertions = (from m in db.Messages
                                     join s in db.MessageSents on m.ID equals s.MessageID
                                     join r in db.MessageRecipients on s.MessageID equals r.MessageID
                                     where (s.SentUserID == userId || s.SentUserID == dashboard.StaticStudent.SupervisorUserId) && (r.ReceiverUserID == userId || r.ReceiverUserID == dashboard.StaticStudent.SupervisorUserId)
                                     orderby m.SentTime descending
                                     select new Convertion { message = m, messageSent = s, messageRecipient = r }).ToList();//Get Convertion between Student and Supervision
            dashboard.SMConvertions = (from m in db.Messages
                                       join s in db.MessageSents on m.ID equals s.MessageID
                                       join r in db.MessageRecipients on s.MessageID equals r.MessageID
                                       where (s.SentUserID == userId || s.SentUserID == dashboard.StaticStudent.SecondMarkerUserId) && (r.ReceiverUserID == userId || r.ReceiverUserID == dashboard.StaticStudent.SecondMarkerUserId)
                                       orderby m.SentTime descending
                                       select new Convertion { message = m, messageSent = s, messageRecipient = r }).ToList();//Get Convertion between Student and Second marker
            dashboard.Uploadedfiles = (from d in db.Documents where d.CreatedByUserId == dashboard.StaticStudent.SupervisorUserId orderby d.CreatedTime descending select d).ToList(); // Get uploaded files by Supervision
            dashboard.SMUploadedfiles = (from d in db.Documents where d.CreatedByUserId == dashboard.StaticStudent.SecondMarkerUserId orderby d.CreatedTime descending select d).ToList();// Get uploaded files by Second marker
            dashboard.RequestedMeetings = (from m in db.MeetingEvents where m.OrganizerUserID == dashboard.StaticStudent.SupervisorUserId orderby m.MeetingEventID descending select m).ToList();// Get Requested meetings by Supervision
            dashboard.SMRequestedMeetings = (from m in db.MeetingEvents where m.OrganizerUserID == dashboard.StaticStudent.SecondMarkerUserId orderby m.MeetingEventID descending select m).ToList();// Get Requested meetings by Second marker
            return View(dashboard);
        }

        [Authorize(Roles = "Teacher")]
        public ActionResult TeacherDashboard(string sortOrder, string searchString)
        {
            ViewBag.FstNameSortParm = String.IsNullOrEmpty(sortOrder) ? "fst_name_desc" : ""; // Sort by First Name
            ViewBag.LstNameSortParm = sortOrder == "lst_name_asc" ? "lst_name_desc" : "lst_name_asc"; // Soft by Last Name
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; // Soft by Enrollment Date
            ViewBag.ResponsibilitySortParm = sortOrder == "supervion" ? "scnd_marker" : "supervion"; // Soft by Teacher Responsibility
            DashboardSumarising dashboard = new DashboardSumarising();// Create new View Model
            string userId = User.Identity.GetUserId(); // Get current User
            dashboard.TotalSentMessages = (from m in db.MessageSents where m.SentUserID == userId select m).Count();//Get Total Sent Messages
            dashboard.TotalInboxMessages = (from m in db.MessageRecipients where m.ReceiverUserID == userId select m).Count();//Get Total Inbox Messages
            dashboard.TotalUploadedFiles = (from d in db.Documents where d.CreatedByUserId == userId select d).Count();//Get Total uploaded files
            dashboard.TotalComments = (from c in db.Comments where c.UserId == userId select c).Count();//Get Total Comments in file uploaded
            dashboard.TotalOrganizers = (from m in db.MeetingEvents where m.OrganizerUserID == userId select m).Count();//Get Total Organizer meetings
            dashboard.TotalMeetingNotes = (from m in db.MeetingNotes where m.UserID == userId select m).Count();//Get Total Meeting Notes
            dashboard.TotalRequestedMeetings = (from m in db.MeetingEventParticipants where m.RequestedUserID == userId select m).Count();//Get Total Requested Meetings
            var students = from s in db.Students where s.SupervisorUserId == userId || s.SecondMarkerUserId == userId select s;// Get All Student 
            if (!String.IsNullOrEmpty(searchString))
            {
                students = students.Where(s => s.LastName.Contains(searchString)
                                       || s.FirstName.Contains(searchString));
            }
            switch (sortOrder)
            {
                case "fst_name_desc":
                    students = students.OrderByDescending(s => s.FirstName);
                    break;
                case "lst_name_asc":
                    students = students.OrderBy(s => s.LastName);
                    break;
                case "lst_name_desc":
                    students = students.OrderByDescending(s => s.LastName);
                    break;
                case "Date":
                    students = students.OrderBy(s => s.EnrollmentDate);
                    break;
                case "date_desc":
                    students = students.OrderByDescending(s => s.EnrollmentDate);
                    break;
                case "supervion":
                    students = students.OrderBy(s => s.SupervisorUserId);
                    break;
                case "scnd_marker":
                    students = students.OrderByDescending(s => s.SecondMarker);
                    break;
                default:
                    students = students.OrderBy(s => s.FirstName);
                    break;
            }
            dashboard.Students = students.ToList();  // Get All Student           
            return View(dashboard);
        }

        [Authorize(Roles = "Authorised")]
        public ActionResult StaffDashboard(string sortOrder, string searchString)
        {
            ViewBag.FstNameSortParm = String.IsNullOrEmpty(sortOrder) ? "fst_name_desc" : ""; // Sort by First Name
            ViewBag.LstNameSortParm = sortOrder == "lst_name_asc" ? "lst_name_desc" : "lst_name_asc"; // Soft by Last Name
            ViewBag.BirthdaySortParm = sortOrder == "birth_date" ? "birth_date_desc" : "birth_date"; // Soft by Enrollment Date
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; // Soft by Enrollment Date
            ViewBag.SupervisorSortParm = sortOrder == "supervion_asc" ? "supervion_desc" : "supervion_asc"; // Soft by Supervisor
            ViewBag.MakerSortParm = sortOrder == "marker_asc" ? "marker_desc" : "marker_asc"; // Soft by Second Marker
            ViewBag.StaffSortParm = sortOrder == "staff_asc" ? "staff_desc" : "staff_asc"; // Soft by Second Marker
            DashboardSumarising dashboard = new DashboardSumarising();// Create new View Model
            string userId = User.Identity.GetUserId(); // Get current User
            var students = from s in db.Students select s;// Get All Student 
            if (!String.IsNullOrEmpty(searchString))
            {
                students = students.Where(s => s.LastName.Contains(searchString)
                                       || s.FirstName.Contains(searchString));
            }
            switch (sortOrder)
            {
                case "fst_name_desc":
                    students = students.OrderByDescending(s => s.FirstName);
                    break;
                case "lst_name_asc":
                    students = students.OrderBy(s => s.LastName);
                    break;
                case "lst_name_desc":
                    students = students.OrderByDescending(s => s.LastName);
                    break;
                case "birth_date":
                    students = students.OrderBy(s => s.Birthday);
                    break;
                case "birth_date_desc":
                    students = students.OrderByDescending(s => s.Birthday);
                    break;
                case "Date":
                    students = students.OrderBy(s => s.EnrollmentDate);
                    break;
                case "date_desc":
                    students = students.OrderByDescending(s => s.EnrollmentDate);
                    break;
                case "supervion_asc":
                    students = students.OrderBy(s => s.Supervisor.FirstName);
                    break;
                case "supervion_desc":
                    students = students.OrderByDescending(s => s.Supervisor.FirstName);
                    break;
                case "marker_asc":
                    students = students.OrderBy(s => s.SecondMarker.FirstName);
                    break;
                case "marker_desc":
                    students = students.OrderByDescending(s => s.SecondMarker.FirstName);
                    break;
                case "staff_asc":
                    students = students.OrderBy(s => s.AuthorisedStaff.FirstName);
                    break;
                case "staff_desc":
                    students = students.OrderByDescending(s => s.AuthorisedStaff.FirstName);
                    break;
                default:
                    students = students.OrderBy(s => s.FirstName);
                    break;
            }
            dashboard.Students = students.ToList();  // Get All Student           
            return View(dashboard);
        }
        [Authorize(Roles = "Authorised")]
        public ActionResult StudentDetails(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DashboardSumarising dashboard = new DashboardSumarising();// Create new View Model
            dashboard.StaticStudent = db.Students.Find(id);//Get supervision and second marker profile
            if (dashboard.StaticStudent == null)
            {
                return HttpNotFound();
            }
            dashboard.TotalSentMessages = (from m in db.MessageSents where m.SentUserID == id select m).Count();//Get Total Sent Messages
            dashboard.TotalInboxMessages = (from m in db.MessageRecipients where m.ReceiverUserID == id select m).Count();//Get Total Inbox Messages
            dashboard.TotalUploadedFiles = (from d in db.Documents where d.CreatedByUserId == id select d).Count();//Get Total uploaded files
            dashboard.TotalComments = (from c in db.Comments where c.UserId == id select c).Count();//Get Total Comments in file uploaded
            dashboard.TotalRequestedMeetings = (from m in db.MeetingEventParticipants where m.RequestedUserID == id select m).Count();//Get Total Requested Meetings
            dashboard.Convertions = (from m in db.Messages
                                     join s in db.MessageSents on m.ID equals s.MessageID
                                     join r in db.MessageRecipients on s.MessageID equals r.MessageID
                                     where (s.SentUserID == id || s.SentUserID == dashboard.StaticStudent.SupervisorUserId) && (r.ReceiverUserID == id || r.ReceiverUserID == dashboard.StaticStudent.SupervisorUserId)
                                     orderby m.SentTime descending
                                     select new Convertion { message = m, messageSent = s, messageRecipient = r }).ToList();//Get Convertion between Student and Supervision
            dashboard.SMConvertions = (from m in db.Messages
                                       join s in db.MessageSents on m.ID equals s.MessageID
                                       join r in db.MessageRecipients on s.MessageID equals r.MessageID
                                       where (s.SentUserID == id || s.SentUserID == dashboard.StaticStudent.SecondMarkerUserId) && (r.ReceiverUserID == id || r.ReceiverUserID == dashboard.StaticStudent.SecondMarkerUserId)
                                       orderby m.SentTime descending
                                       select new Convertion { message = m, messageSent = s, messageRecipient = r }).ToList();//Get Convertion between Student and Second marker
            dashboard.Uploadedfiles = (from d in db.Documents where d.CreatedByUserId == dashboard.StaticStudent.SupervisorUserId || d.CreatedByUserId == id orderby d.CreatedTime descending select d).ToList(); // Get uploaded files by Supervision
            dashboard.SMUploadedfiles = (from d in db.Documents where d.CreatedByUserId == dashboard.StaticStudent.SecondMarkerUserId || d.CreatedByUserId == id orderby d.CreatedTime descending select d).ToList();// Get uploaded files by Second marker
            dashboard.RequestedMeetings = (from m in db.MeetingEvents where m.OrganizerUserID == dashboard.StaticStudent.SupervisorUserId orderby m.MeetingEventID descending select m).ToList();// Get Requested meetings by Supervision
            dashboard.SMRequestedMeetings = (from m in db.MeetingEvents where m.OrganizerUserID == dashboard.StaticStudent.SecondMarkerUserId orderby m.MeetingEventID descending select m).ToList();// Get Requested meetings by Second marker
            return View(dashboard);
        }
        [Authorize(Roles = "Teacher")]
        public ActionResult StudentActivities(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            StudentActivitiesVM student = new StudentActivitiesVM();
            string userId = User.Identity.GetUserId();
            student.StaticStudent = db.Students.Find(id); //Get Student profile
            if (student.StaticStudent == null)
            {
                return HttpNotFound();
            }
            student.MessageRecipients = (from m in db.Messages
                                         join r in db.MessageRecipients on m.ID equals r.MessageID
                                         where r.ReceiverUserID == userId && m.SentByUserId == id
                                         orderby r.ReceivedTime descending
                                         select r).ToList(); //Get Received Messages
            student.Documents = (from d in db.Documents
                                 where d.CreatedByUserId == id
                                 orderby d.CreatedTime descending
                                 select d).ToList(); //Get Uploaded Documents
            return View(student);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
